const Promise = require('./es6-promise').Promise
let addPromise = {}; //封装过的包含promise的wx API


/* POST 请求 */
addPromise.post = ((url, data) => { 
  return new Promise((resolve, reject) => {
    wx.request({
        url: url,
        method: 'POST',
        data: data,
        success: res => resolve(res),
        fail: err => reject(err),
    })
  })
})
/* GET 请求 */
addPromise.get = ((url, data = {}) => {
  return new Promise((resolve, reject) => {
    wx.request({
        url: url,
        method: 'GET',
        data: data,
        success: res => resolve(res),
        fail: err => reject(err),
    })
  })
})

/*wx.login*/
addPromise.login = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success: function (res) {
        resolve(res);
      }
    })
  })
};


/*wx.setStorage*/
addPromise.setStorage = (key, value) => {
  return new Promise((resolve, reject) => {
    wx.setStorage({
      key: key,
      data: value,
      success: res => {
        resolve(value);//将数据传给回调
      },
      fail: err => {
        reject(err)
      }
    })
  })
};

/*wx.getStorage*/
addPromise.getStorage = key => {
  return new Promise((resolve, reject) => {
    wx.getStorage({
      key: key,
      success: res => {
        resolve(res)
      },
      fail: err => {
        reject(err) //如果是没取到数据 返回空或undefined
      }
    })
  })
};
/**wx.getLocation */
addPromise.getLocation = ()=>{
  return new Promise((resolve,reject)=>{
    wx.getLocation({
      type:'gcj02',
      success: res=>{resolve(res)},
      fail: err => {reject(err)}
    })
  })

}
/**wx.uploadFile */
addPromise.uploadFile = (url, filePath, name, formData = {}) => {
  return new Promise((resolve,reject)=>{
    wx.uploadFile({
      url: url,
      method: 'POST',
      filePath: filePath,
      name: name, 
      header: {"Content-Type": "multipart/form-data"}, // 设置请求的 header  
      formData: formData, // HTTP 请求中其他额外的 form data  
      success: res=>{
        resolve(res)
      },
      fail: err => {
        reject(err)
      } 
    })
  })
 
} 

/**wx.chooseImage */
addPromise.chooseImage = (count = 1, sizeType = ['original', 'compressed'], sourceType = ['album', 'camera']) =>{
  return new Promise((resolve,reject) =>{
    wx.chooseImage({
      count: count, // 默认9
      sizeType: sizeType, // 可以指定是原图还是压缩图，默认二者都有
      sourceType: sourceType, // 可以指定来源是相册还是相机，默认二者都有
      success: (res) => {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        let tempFilePaths = res.tempFilePaths
        resolve(res)
      },
      fail: err => { 
        reject(err)
      } 
    }) 
  })
}


module.exports = addPromise
